package server

import (
	models "fileshare/controller/modles"
	"fileshare/sqlconn"
	"fileshare/utils"
	"time"
)

/**
* @program: fileshare
*
* @description:
*
* @author: Koco.Allien
*
* @create: 2020-04-05 18:57
**/
//ISExist 判断用户的登录信息是否在数据库中有效，返回是否含有和用户对象
func ISExist(account, passwd string) (bool, models.UserInfo) {
	utils.MsgToLog("login的post的参数信息account:" + account + "passwd:" + passwd)
	var user models.UserInfo
	//MyDB.First(&user)
	sqlconn.MyDB.Model(&models.UserInfo{}).Where(&models.UserInfo{Account: account, Password: passwd}).Find(&user)
	//为何是空的数据，db拿不到返回的数据
	utils.MsgToLog("查询用户登录信息的结果"+user.Name+" : ", user.ID)
	if user.Name == "" {
		return false, models.UserInfo{}
	}
	return true, user
}

//注册账户
func CreateUser(account string, passwd1 string) bool {

	i := sqlconn.MyDB.Find(&models.UserInfo{}, "account=?", account).RowsAffected
	utils.MsgToLog("注册账户的id信息: ", i)
	if i == 1 {
		return false
	} else {
		sqlconn.MyDB.Create(&models.UserInfo{
			CreateAt: time.Now().Local(),
			UpdateAt: time.Now().Local(),
			Name:     account,
			Account:  account,
			Password: passwd1,
			Role:     1,
		})
		return true
	}

}

func GetUser(uid int) (user models.UserInfo) {
	sqlconn.MyDB.Model(&models.UserInfo{}).Where("id = ? ", uid).Find(&user)
	return
}

func DelUser(uid int) {
	sqlconn.MyDB.Delete(&models.UserInfo{ID: uid})
}

func GetUsers(offset, limit int) (users []*models.UserInfo, count int) {
	sqlconn.MyDB.Model(&models.UserInfo{}).Count(&count).
		Order("create_at desc").Offset(offset).Limit(limit).Find(&users)
	return
}

func Updateuser(u *models.UserInfo) error {
	return sqlconn.MyDB.Model(&models.UserInfo{}).Update(u).Error
}
